/*
 * @Author: 朱自强
 * @Date: 2024-03-08 19:28:49
 * @LastEditors: 朱自强
 * @LastEditTime: 2025-02-10 16:43:04
 * @FilePath: \a-lot-of-test-vue3\src\utils\utils.ts
 * @Description:
 *
 * Copyright (c) 2024 by 朱自强, All Rights Reserved.
 */
import type { Component } from "vue";
import { h } from "vue";
import moment from "moment";
/**
 * 将数组转成树结构
 * @param {Array} data 数组
 * @param {String} key 依据哪个字段分层级
 * @param {String} parentPropName 层级字段名称
 * @param {String} childrenName 子集集合名称
 * @returns {Array} 返回结果，树形结构
 */
export function listToTree(
  data: any[],
  key: string,
  parentPropName: string,
  childrenName: string
): any[] {
  const result: any[] = [];
  data.forEach((item: any) => {
    item[childrenName] = [];
  });
  const map: any = {};
  data.forEach((item: any) => {
    if (key.indexOf(".") > -1) {
      map[item[key.split(".")[0]][key.split(".")[1]]] = item;
    } else {
      map[item[key]] = item;
    }
  });
  data.forEach((item: any) => {
    const parent =
      parentPropName.indexOf(".") > -1
        ? map[item[parentPropName.split(".")[0]][parentPropName.split(".")[1]]]
        : map[item[parentPropName]];
    if (parent) {
      (parent[childrenName] || (parent[childrenName] = [])).push(item);
    } else {
      result.push(item);
    }
  });
  return result;
}

/**
 * 树转数组
 * @param {Array} treeData 树结构数据
 * @param {String} childrenName 子集集合名称
 * @returns {Array} 返回结果，数组
 */
export function treeToList(treeData: any[], childrenName: string): any[] {
  const stack: any[] = treeData;
  const data: any[] = [];
  while (stack.length !== 0) {
    const pop: any = stack.pop();
    data.unshift(pop);
    const children = pop[childrenName];
    if (children) {
      for (let i = children.length - 1; i >= 0; i--) {
        stack.unshift(children[i]);
      }
    }
  }
  return data;
}
// 生成uuid
export function getUUID(): string {
  const s: any = [];
  const hexDigits = "0123456789abcdef";
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";
  const uuid = s.join("");
  return uuid;
}
// 日期格式化
export function dateFormat(date: string | number | Date, fmt: string): string {
  if (typeof date === "number") {
    date = new Date(date);
  }
  if (typeof date === "object") {
    date = moment(date).format(fmt);
  }
  return date;
}
